﻿#include <fstream>
#include <iostream>
#include <filesystem>
#include <json/json.h>
#include "Utils/Log.h"
#include "Config.h"

namespace AVSAnalyzer 
{
    Config::Config(const char* file) :
        file(file)
    {
        std::ifstream ifs(file, std::ios::binary);

        if (!ifs.is_open()) 
        {
            LOGE("open %s error", file);
            return;
        }
        else 
        {
            Json::CharReaderBuilder builder;
            builder["collectComments"] = true;
            JSONCPP_STRING errs;
            Json::Value root;

            if (parseFromStream(builder, ifs, &root, &errs)) 
            {
                this->alarmHost = root["alarmHost"].asString();
                this->analyzerHost = root["analyzerHost"].asString();
                this->mediaHost = root["mediaHost"].asString();
                this->mediaRtspPort = root["mediaRtspPort"].asInt();
                this->analyzerPort = root["analyzerPort"].asInt();
                this->uploadDir = root["uploadDir"].asString();
                this->modelDir = root["modelDir"].asString();
                this->algorithmApiUrl = root["algorithmApiUrl"].asString();

                std::filesystem::path path(uploadDir);          // 上传文件夹路径
                try 
                {
                    if (!std::filesystem::exists(path)) 
                    {
                        std::filesystem::create_directory(path);
                    }

                    mState = true;
                }
                catch (std::filesystem::filesystem_error& e) 
                {
                    std::cout << e.what() << std::endl;
                }              
            }
            else 
            {
                LOGE("parse %s error", file);
            }
            ifs.close();
        }
    }

    Config::~Config()
    {
    }

    void Config::show() 
    {
        printf("config.file=%s\n", file);        
        printf("config.analyzerHost=%s\n", analyzerHost.data());
        printf("config.mediaHost=%s\n", mediaHost.data());
        printf("config.mediaRtspPort=%d\n", mediaRtspPort);
        printf("config.uploadDir=%s\n", uploadDir.data());
        printf("config.modelDir=%s\n", modelDir.data());
        printf("config.alarmHost=%s\n", alarmHost.data());
        printf("config.algorithmApiUrl=%s\n", algorithmApiUrl.data());
    }
}
